import cv2
import threading

cap = cv2.VideoCapture(0)  # 开启摄像头
cap.set(cv2.CAP_PROP_FRAME_WIDTH,640) 
cap.set(cv2.CAP_PROP_FRAME_HEIGHT,480)
cap.set(cv2.CAP_PROP_FPS,30)
# 循环读取图像
while True:
    ok, faceImg = cap.read()  # 读取摄像头图像
    if ok is False:
        print('无法读取到摄像头！')
        break
    
   
#    faceImg = img
    high=faceImg.shape[0]
    width=faceImg.shape[1]
#    print(width,high)
    gray = cv2.cvtColor(faceImg,cv2.COLOR_BGR2GRAY)
    classifier = cv2.CascadeClassifier('/home/l1015/Camera/颜色识别跟踪/haarcascade_frontalface_alt.xml')
    # 加载人脸识别分类器
    # 官方已有的分类器  https://github.com/opencv/opencv/tree/master/data/haarcascades
    # github的不好下载, 可以从码云上找
    # Python\Python38-32\Lib\site-packages\cv2\data  这个目录下也有
    

    # 识别器进行识别
    
    
    def track():
        faceRects = classifier.detectMultiScale(gray,scaleFactor=1.2,minNeighbors=3,minSize=(32, 32))
        if len(faceRects):
            for faceRect in faceRects:
                x,y,w,h = faceRect
                # 框选出人脸   最后一个参数2是框线宽度
                cv2.rectangle(faceImg,(x, y), (x + w, y + h), (0,255,0), 2)
                print((x+w/2)-width/2)
#                print(x+w/2)
 #               if x+w/2 > width/2+50:
  #                  print("Left")
   #             elif x+w/2 < width/2-50:
    #                print("Right")
     #           elif width/2-50 < x+w/2 < width/2+50:
      #              print("Central")
                    
    

    
    
    
#    # 转换灰色
#    gray = cv2.cvtColor(faceImg,cv2.COLOR_BGR2GRAY)
#
#    # 加载人脸识别分类器
#    # 官方已有的分类器  https://github.com/opencv/opencv/tree/master/data/haarcascades
#    # github的不好下载, 可以从码云上找
#    # Python\Python38-32\Lib\site-packages\cv2\data  这个目录下也有
#    classifier = cv2.CascadeClassifier('haarcascade_eye.xml')
#    color = (255,0,0)
#
#    # 识别器进行识别
#    faceRects = classifier.detectMultiScale(gray,scaleFactor=1.2,minNeighbors=3,minSize=(32, 32))
#
#    if len(faceRects):
#        for faceRect in faceRects:
#            x,y,w,h = faceRect
#            # 框选出人脸   最后一个参数2是框线宽度
#            cv2.rectangle(faceImg,(x, y), (x + h, y + w), color, 2)
#            
#    
    #faceImg= cv2.cvtColor(faceImg,cv2.COLOR_RGB2BGR)
    cv2.imshow("faceImg",faceImg)
    # 展示图像
    
    thread = threading.Thread(target=track)
    thread.start()

    k = cv2.waitKey(10)  # 键盘值
    if k == 27:   # 通过esc键退出摄像
        break

# 关闭摄像头
cap.release()
cv2.destroyAllWindows()


